package com.springclouddemo.gatewayzuulaggregation.controllers;

import com.google.common.collect.Maps;
import com.springclouddemo.gatewayzuulaggregation.services.AggregationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import rx.Observable;
import rx.Observer;

import java.util.HashMap;

/**
 * @author 何昌杰
 */

@RestController
public class AggregationController {
    public static final Logger LOGGER = LoggerFactory.getLogger(AggregationController.class);

    @Autowired
    private AggregationService aggregationService;

    @GetMapping("/aggregate/{name}")
    public DeferredResult<HashMap<String, String>> aggregate(@PathVariable String name) {
        Observable<HashMap<String, String>> result = this.aggregateObservable(name);
        return this.toDeferredResult(result);
    }

    public Observable<HashMap<String, String>> aggregateObservable(String name) {
        // 合并两个或者多个Observables发射出的数据项，根据指定的函数变换它们
        return Observable.zip(
                this.aggregationService.helloDemo1(name),
                this.aggregationService.helloDemo1(name),
                (res1, res2) -> {
                    HashMap<String, String> map = Maps.newHashMap();
                    map.put("microservice1", res1);
                    map.put("microservice2", res2);
                    return map;
                }
        );
    }

    public DeferredResult<HashMap<String, String>> toDeferredResult(Observable<HashMap<String, String>> details) {
        DeferredResult<HashMap<String, String>> result = new DeferredResult<>();
        // 订阅
        details.subscribe(new Observer<HashMap<String, String>>() {
            @Override
            public void onCompleted() {
                LOGGER.info("完成...");
            }

            @Override
            public void onError(Throwable throwable) {
                LOGGER.error("发生错误...", throwable);
            }

            @Override
            public void onNext(HashMap<String, String> movieDetails) {
                result.setResult(movieDetails);
            }
        });
        return result;
    }
}
